using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BlazorAdmin.Web.Shared.Components;
using BlazorAdmin.Web.Shared.Services;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace BlazorAdmin.Web.Shared.Pages.Admin
{
    /// <summary>
    /// Organize.razor 页面代码
    /// </summary>
    public partial class Organizes
    {
        private Organize? Organize { get; set; }

        private List<TreeViewItem<Organize>>? OrganizeTree { get; set; }

        private Organize? SelectedOrganize { get; set; }

        private DialogOption? Option { get; set; }

        protected override async void OnInitialized()
        {
            base.OnInitialized();

            OrganizeTree = await OrganizeService?.GetOrganizeTree(AppContext?.LoginName);
        }

        private async Task EditOrganize(bool isCreate = false)
        {
            if (isCreate)
            {
                Organize = new Organize()
                {
                    IsEnable = true,
                    ModifyUser = AppContext?.LoginName,
                    ModifyTime = DateTime.Now
                };
            }
            else
            {
                if (SelectedOrganize == null)
                {
                    MsgService?.Show(new() { Content = "请选择要修改的组织" });
                    return;
                }
                else if (SelectedOrganize.OrgCode.ToLower() == "default") // 默认的分组（未分组）不允许修改
                {
                    MsgService?.Show(new() { Content = "系统默认组织，不允许编辑" });
                    return;
                }

                Organize = SelectedOrganize;
            }

            Option = new DialogOption()
            {
                Title = isCreate ? "创建组织" : "修改组织",
                Size = Size.Large,
                BodyTemplate = BootstrapDynamicComponent.CreateComponent<OrganizeEdit>(new Dictionary<string, object?>()
                {
                    [nameof(OrganizeEdit.Value)] = Organize // Value是引用类型，不需要再定义ValueChanged回调方法，如果值类型，则必须定义
                }).Render(),
                FooterTemplate = BootstrapDynamicComponent.CreateComponent<Button>(new Dictionary<string, object?>
                {
                    [nameof(Button.Color)] = Color.Primary,
                    [nameof(Button.Text)] = "保存",
                    [nameof(Button.Icon)] = "fa-solid fa-fw fa-check",
                    [nameof(Button.OnClick)] = EventCallback.Factory.Create<MouseEventArgs>(this, async () =>
                    {
                        if (string.IsNullOrEmpty(Organize.OrgName))
                        {
                            MsgService?.Show(new() { Content = "请输入设备组名称" });
                            return;
                        }

                        Organize.ModifyUser = AppContext?.LoginName;
                        Organize.ModifyTime = DateTime.Now;

                        var errMsg = await OrganizeService.Save(Organize);
                        if (!string.IsNullOrEmpty(errMsg))
                        {
                            MsgService?.Show(new() { Content = $"保存失败，{errMsg}", Color = Color.Danger });
                            return;
                        }

                        OrganizeTree = await OrganizeService?.GetOrganizeTree(AppContext?.LoginName); // 保存成功，刷新树
                        Option?.CloseDialogAsync();

                        MsgService?.Show(new() { Content = "保存成功", Color = Color.Success });
                    })
                }).Render()
            };

            _ = DialogService?.Show(Option);
        }

        /// <summary>
        /// 删除组织
        /// </summary>
        private async Task DeleteOrganize()
        {
            if (SelectedOrganize == null)
            {
                MsgService?.Show(new() { Content = "请选择要删除的组织" });
                return;
            }
            else if (SelectedOrganize.OrgCode.ToLower() == "default") // 默认的分组（未分组）不允许删除
            {
                MsgService?.Show(new() { Content = "系统默认组织，不允许删除" });
                return;
            }

            var errMsg = await OrganizeService.Delete(SelectedOrganize.OrgCode);
            if (!string.IsNullOrEmpty(errMsg))
                MsgService?.Show(new() { Content = errMsg });

            OrganizeTree = await OrganizeService?.GetOrganizeTree(AppContext?.LoginName);

            InvokeAsync(StateHasChanged);
        }

        private async Task OnOrganizeClick(TreeViewItem<Organize> items)
        {
            SelectedOrganize = items.Value;
        }

        #region Inject 注入的服务

        [Inject]
        private BootstrapAppContext? AppContext { get; set; }

        [Inject]
        private DialogService? DialogService { get; set; }

        [Inject]
        private MessageService? MsgService { get; set; }

        [Inject]
        private IOrganize? OrganizeService { get; set; }

        #endregion
    }
}
